package com.xjt.field.controller;


import com.xjt.field.entity.FieldTemplate;
import com.xjt.field.entity.Result;
import com.xjt.field.entity.User;
import com.xjt.field.service.ITemplateService;
import com.xjt.field.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xujiangtao
 * @since 2022-02-16
 */
@RestController
@RequestMapping("/field/user")
@AllArgsConstructor
public class UserController {

    private IUserService iUserService;

    private ITemplateService iTemplateService;

    @PostMapping("/list")
    public Result list(){
        return Result.success(iUserService.list());
    }

    @GetMapping("/{id}")
    public Result info(@PathVariable Long id){
        User user = iUserService.getById(id);
        List<FieldTemplate> fieldTemplates = iTemplateService.queryFieldData(1, id);
        user.setFieldTemplateList(fieldTemplates);
        return Result.success(user);
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody User user){
        if (user.getUserName().length()>20 || user.getPwd().length()>20 || user.getAge()>1000){
            return Result.failed("数据量过大，请输入合理测试数据");
        }
        if (user.getId()==null){
            int count = iUserService.count();
            if (count>9){
                return Result.failed("测试数据长度最大不超过10条");
            }
        }
        boolean save = iUserService.saveOrUpdate(user);
        if (save && user.getFieldTemplateList()!=null && user.getFieldTemplateList().size()>0){
            iTemplateService.saveOrUpdateFieldData(user.getFieldTemplateList(), user.getId(),1);
        }
        return Result.success(save);
    }

    @DeleteMapping("/{id}")
    public Result del(@PathVariable Long id){
       return Result.success(iUserService.removeById(id));
    }
}
